import 'dart:io';

import 'package:eason_nebula/ui/Base/EasonBasePage.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class BatteryPage extends EasonBasePage {
  const BatteryPage({Key? key}) : super(key: key);

  @override
  String get title => 'permission'.tr();

  @override
  State<BatteryPage> createState() => _BatteryPageState();
}

class _BatteryPageState extends BasePageState<BatteryPage> {
  // 创建MethodChannel
  static const platform = MethodChannel('com.eason.nebula/permission');
  // 这里可以添加其他需要的状态变量
  String batteryLevel = '未知';
  // 权限状态
  Map<String, String> permissionStatuses = {};
  // 默认音量
  double volume = 0.5;
  // 搞个数组获取相关的权限状态
  List<String> permissions = [
    'microphone',
    'camera',
    'location',
    'notification',
    'photos',
    'contacts',
    'bluetooth',
    'calendar',
    'clipboard',
    'battery',
    'volume',
    'storage',
  ];
  @override
  void initState() {
    super.initState();
    // 监听电量变化
    platform.setMethodCallHandler((call) async {
      if (call.method == 'batteryLevel') {
        setState(() {
          batteryLevel = call.arguments;
        });
      }
    });
  }

  @override
  Widget buildContent(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        _buildPermissionCard('battery'),
        const SizedBox(height: 40),
        ...permissions.map(_buildPermissionCard).toList(),
      ],
    );
  }

  Widget _buildPermissionCard(String type) {
    final status = permissionStatuses[type] ?? '未知';
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Wrap(
              children: [
                Icon(Icons.security, color: Colors.blue),
                const SizedBox(width: 8),
                Text(
                  '$type 权限状态:',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const SizedBox(width: 8),
                Text(
                  status,
                  style: TextStyle(fontSize: 16, color: Colors.black87),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Align(
              alignment: Alignment.centerRight,
              child: ElevatedButton(
                onPressed: () => _getPermissionStatus(type),
                child: Text('请求 $type 权限'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<dynamic> invokeMethod(String method, [dynamic arguments]) async {
    try {
      final MethodChannel channel = MethodChannel(
        'com.eason.nebula/permission',
      );
      return await channel.invokeMethod(method, arguments);
    } on PlatformException catch (e) {
      debugPrint("Failed to invoke $method: '${e.message}'.");
      return null;
    }
  }

  // 获取权限状态
  Future<void> _getPermissionStatus(String type) async {
    final result = await invokeMethod('requestPermission', {'type': type});
    setState(() {
      permissionStatuses[type] = result?.toString() ?? '调用失败';
    });
  }

  // 调用在原生端的获取电池信息的方法
  Future<void> _getBatteryLevel() async {
    try {
      final int result = await platform.invokeMethod('getBatteryLevel');
      debugPrint('Battery level: $result%');
      if (Platform.isAndroid) debugPrint('Android 设备');
      if (Platform.isIOS) debugPrint('iOS 设备');
      // 更新状态
      setState(() {
        batteryLevel = result.toString();
      });
    } on PlatformException catch (e) {
      setState(() {
        batteryLevel = "获取电量失败: '${e.message}'.";
      });
    }
  }
}
